package com.example.service.impl;

import com.example.common.Result;
import com.example.dto.PermissionDTO;
import com.example.entity.Permission;
import com.example.entity.RolePermission;
import com.example.entity.UserRole;
import com.example.mapper.PermissionMapper;
import com.example.mapper.RolePermissionMapper;
import com.example.mapper.UserRoleMapper;
import com.example.service.PermissionService;
import com.example.service.MenuService;
import com.example.vo.PermissionVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionMapper permissionMapper;
    
    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    
    @Autowired
    private UserRoleMapper userRoleMapper;
    
    @Autowired
    private MenuService menuService;

    @Override
    @Transactional
    public Result<String> addPermission(PermissionDTO permissionDTO) {
        try {
            // 检查权限编码是否重复
            Permission existingPermission = permissionMapper.selectByCode(permissionDTO.getPermissionCode());
            if (existingPermission != null) {
                return Result.error("权限编码已存在");
            }
            
            Permission permission = new Permission();
            BeanUtils.copyProperties(permissionDTO, permission);
            permission.setCreateTime(LocalDateTime.now());
            permission.setUpdateTime(LocalDateTime.now());
            permission.setDeleted(0);
            
            // 如果没有设置父权限ID，设为0
            if (permission.getParentId() == null) {
                permission.setParentId(0L);
            }
            
            // 如果没有设置状态，默认启用
            if (permission.getStatus() == null) {
                permission.setStatus(1);
            }
            
            // 如果没有设置排序，默认为0
            if (permission.getSort() == null) {
                permission.setSort(0);
            }

            int result = permissionMapper.insert(permission);
            if (result > 0) {
                return Result.success("新增权限成功");
            }
            return Result.error("新增权限失败");
        } catch (Exception e) {
            return Result.error("新增权限失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<String> updatePermission(Long id, PermissionDTO permissionDTO) {
        try {
            Permission existingPermission = permissionMapper.selectById(id);
            if (existingPermission == null) {
                return Result.error("权限不存在");
            }
            
            // 检查权限编码是否重复（排除当前权限）
            Permission codeCheck = permissionMapper.selectByCode(permissionDTO.getPermissionCode());
            if (codeCheck != null && !codeCheck.getId().equals(id)) {
                return Result.error("权限编码已存在");
            }

            Permission permission = new Permission();
            BeanUtils.copyProperties(permissionDTO, permission);
            permission.setId(id);
            permission.setUpdateTime(LocalDateTime.now());
            
            // 保持原有的创建时间和删除状态
            permission.setCreateTime(existingPermission.getCreateTime());
            permission.setDeleted(existingPermission.getDeleted());

            int result = permissionMapper.updateById(permission);
            if (result > 0) {
                return Result.success("修改权限成功");
            }
            return Result.error("修改权限失败");
        } catch (Exception e) {
            return Result.error("修改权限失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<String> deletePermission(Long id) {
        try {
            Permission permission = permissionMapper.selectById(id);
            if (permission == null) {
                return Result.error("权限不存在");
            }

            // 检查是否有子权限
            List<Permission> children = permissionMapper.selectByParentId(id);
            if (children != null && !children.isEmpty()) {
                return Result.error("该权限下还有子权限，无法删除");
            }

            // 删除角色权限关联关系
            rolePermissionMapper.deleteByPermissionId(id);

            // 删除权限
            int result = permissionMapper.deleteById(id);
            if (result > 0) {
                return Result.success("删除权限成功");
            }
            return Result.error("删除权限失败");
        } catch (Exception e) {
            return Result.error("删除权限失败：" + e.getMessage());
        }
    }

    @Override
    public Result<PermissionVO> getPermissionById(Long id) {
        try {
            Permission permission = permissionMapper.selectById(id);
            if (permission == null) {
                return Result.error("权限不存在");
            }

            PermissionVO permissionVO = new PermissionVO();
            BeanUtils.copyProperties(permission, permissionVO);
            return Result.success(permissionVO);
        } catch (Exception e) {
            return Result.error("查询权限失败：" + e.getMessage());
        }
    }

    @Override
    public Result<List<PermissionVO>> getAllPermissions() {
        try {
            List<Permission> permissions = permissionMapper.selectAll();
            List<PermissionVO> permissionVOs = permissions.stream().map(permission -> {
                PermissionVO permissionVO = new PermissionVO();
                BeanUtils.copyProperties(permission, permissionVO);
                return permissionVO;
            }).collect(Collectors.toList());

            // 构建树形结构
            List<PermissionVO> tree = buildPermissionTree(permissionVOs, 0L);
            return Result.success(tree);
        } catch (Exception e) {
            return Result.error("查询权限列表失败：" + e.getMessage());
        }
    }

    @Override
    public Result<List<PermissionVO>> getPermissionsByType(String permissionType) {
        try {
            List<Permission> permissions = permissionMapper.selectByType(permissionType);
            List<PermissionVO> permissionVOs = permissions.stream().map(permission -> {
                PermissionVO permissionVO = new PermissionVO();
                BeanUtils.copyProperties(permission, permissionVO);
                return permissionVO;
            }).collect(Collectors.toList());

            return Result.success(permissionVOs);
        } catch (Exception e) {
            return Result.error("查询权限列表失败：" + e.getMessage());
        }
    }

    @Override
    public Result<List<PermissionVO>> getEnabledPermissions() {
        try {
            List<Permission> permissions = permissionMapper.selectByStatus(1);
            List<PermissionVO> permissionVOs = permissions.stream().map(permission -> {
                PermissionVO permissionVO = new PermissionVO();
                BeanUtils.copyProperties(permission, permissionVO);
                return permissionVO;
            }).collect(Collectors.toList());

            // 构建树形结构
            List<PermissionVO> tree = buildPermissionTree(permissionVOs, 0L);
            return Result.success(tree);
        } catch (Exception e) {
            return Result.error("查询启用权限列表失败：" + e.getMessage());
        }
    }

    @Override
    public Result<List<PermissionVO>> getPermissionsByParentId(Long parentId) {
        try {
            List<Permission> permissions = permissionMapper.selectByParentId(parentId);
            List<PermissionVO> permissionVOs = permissions.stream().map(permission -> {
                PermissionVO permissionVO = new PermissionVO();
                BeanUtils.copyProperties(permission, permissionVO);
                return permissionVO;
            }).collect(Collectors.toList());

            return Result.success(permissionVOs);
        } catch (Exception e) {
            return Result.error("查询子权限列表失败：" + e.getMessage());
        }
    }

    @Override
    public List<String> getUserPermissions(Long userId) {
        try {
            // 1. 获取用户角色
            List<UserRole> userRoles = userRoleMapper.selectByUserId(userId);
            if (userRoles.isEmpty()) {
                return new ArrayList<>();
            }

            // 2. 获取角色ID列表
            List<Long> roleIds = userRoles.stream()
                    .map(UserRole::getRoleId)
                    .collect(Collectors.toList());

            // 3. 获取角色权限关联
            List<RolePermission> rolePermissions = rolePermissionMapper.selectByRoleIds(roleIds);
            if (rolePermissions.isEmpty()) {
                return new ArrayList<>();
            }

            // 4. 获取权限ID列表
            List<Long> permissionIds = rolePermissions.stream()
                    .map(RolePermission::getPermissionId)
                    .distinct()
                    .collect(Collectors.toList());

            // 5. 获取权限详情
            List<Permission> permissions = permissionMapper.selectByIds(permissionIds);
            
            // 6. 返回启用的权限编码列表
            return permissions.stream()
                    .filter(permission -> permission.getStatus() == 1) // 只返回启用的权限
                    .map(Permission::getPermissionCode)
                    .filter(code -> code != null && !code.trim().isEmpty()) // 过滤空权限编码
                    .collect(Collectors.toList());
        } catch (Exception e) {
            // 记录错误日志，但不中断流程
            System.err.println("获取用户权限失败: userId=" + userId + ", error=" + e.getMessage());
            return new ArrayList<>();
        }
    }

    @Override
    public String getPermissionDescription(String permissionCode) {
        try {
            Permission permission = permissionMapper.selectByCode(permissionCode);
            if (permission != null) {
                return permission.getPermissionName();
            }
            return null;
        } catch (Exception e) {
            System.err.println("获取权限描述失败: permissionCode=" + permissionCode + ", error=" + e.getMessage());
            return null;
        }
    }

    /**
     * 构建权限树形结构
     */
    private List<PermissionVO> buildPermissionTree(List<PermissionVO> permissions, Long parentId) {
        return permissions.stream()
                .filter(permission -> {
                    if (parentId == null || parentId == 0L) {
                        return permission.getParentId() == null || permission.getParentId() == 0L;
                    } else {
                        return parentId.equals(permission.getParentId());
                    }
                })
                .map(permission -> {
                    List<PermissionVO> children = buildPermissionTree(permissions, permission.getId());
                    permission.setChildren(children);
                    return permission;
                })
                .sorted((p1, p2) -> {
                    // 按照sort字段排序
                    int sort1 = p1.getSort() != null ? p1.getSort() : 0;
                    int sort2 = p2.getSort() != null ? p2.getSort() : 0;
                    return Integer.compare(sort1, sort2);
                })
                .collect(Collectors.toList());
    }
} 